import React, { useEffect, useState, useMemo } from 'react';
import { Select, Cascader } from 'antd';
import { commonService } from '@/flowService';

const DataTypeEnum = {
  Basic: 1,
  Object: 3,
  List: 2,
};

const DataTypeSelect = ({
  value,
  onChange,
  type,
  disabled,
  size = 'default',
}) => {
  const [dataTypeList, setDataTypeList] = useState([]);

  const loadData = async () => {
    const res = await commonService.dataType.getList();
    setDataTypeList(res || []);
  };

  useEffect(() => {
    loadData();
  }, []);

  const cascaderProps = {
    expandTrigger: 'hover',
  };

  const options = useMemo(() => {
    const basicTypeList = dataTypeList.filter(item => item.dataTypeClassify === DataTypeEnum.Basic);
    const objectTypeList = dataTypeList.filter(item => item.dataTypeClassify === DataTypeEnum.Object);

    const basicNode = {
      value: 'Basic',
      label: '基础类型',
      children: basicTypeList.map(item => ({ value: item.type, label: item.displayName })),
    };

    const objectNode = {
      value: 'Object',
      label: '对象类型',
      children: objectTypeList.map(item => ({ value: item.objectKey, label: item.displayName })),
    };

    const listNode = {
      value: 'List',
      label: '列表类型',
      children: [basicNode, objectNode].map(node => ({
        ...node,
        children: node.children.map(child => ({
          ...child,
          label: `[ ${child.label} ]`,
        })),
      })),
    };

    return [basicNode, listNode, objectNode];
  }, [dataTypeList]);

  const typeToArray = (type, dataType) => {
    const item = dataTypeList.find(item => item.type === type);
    if (!item) {
      return [];
    }
    if (item.dataTypeClassify === DataTypeEnum.Basic) {
      return ['Basic', type];
    } else if (item.dataTypeClassify === DataTypeEnum.Object) {
      return ['Object', dataType.objectKey];
    } else if (item.dataTypeClassify === DataTypeEnum.List) {
      return ['List', ...typeToArray(dataType.itemType, dataType)];
    }
    return [];
  };

  const arrayToType = (arr) => {
    if (!Array.isArray(arr) || arr.length === 0) {
      return null;
    }
    const result = {
      type: '',
      itemType: null,
      objectKey: null,
      objectStructure: null,
    };
    if (arr[0] === 'Basic') {
      result.type = arr[1];
    } else if (arr[0] === 'Object') {
      result.type = 'Object';
      result.objectKey = arr[1];
    } else if (arr[0] === 'List') {
      result.type = 'List';
      if (arr[1] === 'Basic') {
        result.itemType = arr[2];
      } else if (arr[1] === 'Object') {
        result.itemType = 'Object';
        result.objectKey = arr[2];
      }
    }
    if (result.objectKey) {
      const item = dataTypeList.find(item => item.objectKey === result.objectKey);
      if (item) {
        result.objectStructure = item.objectStructure;
      }
    }
    return result;
  };

  const modelValueObj = useMemo(() => {
    let val = null;
    if (value) {
      val = { ...value };
    }
    return val;
  }, [value]);

  const innerValue = useMemo(() => {
    let val = modelValueObj;
    let result = [];
    if (!val) {
      return result;
    }
    result = typeToArray(val.type, val);
    return result;
  }, [modelValueObj, dataTypeList]);

  const innerBasicValue = useMemo(() => {
    if (innerValue[0] === 'Basic') {
      return innerValue[1];
    }
    return null;
  }, [innerValue]);

  const handleChange = (val) => {
    if (!Array.isArray(val)) {
      onChange?.(null);
      return;
    }
    const result = arrayToType(val);
    onChange?.(result);
  };

  const handleBasicChange = (val) => {
    if (!val) {
      onChange?.(null);
      return;
    }
    let result = {
      type: val,
      itemType: null,
      objectKey: null,
      objectStructure: null,
    };
    onChange?.(result);
  };

  if (type === 'basic') {
    return (
      <Select
        size={size}
        value={innerBasicValue}
        disabled={disabled}
        onChange={handleBasicChange}
      >
        {options[0]?.children?.map(item => (
          <Select.Option key={item.value} value={item.value}>
            {item.label}
          </Select.Option>
        ))}
      </Select>
    );
  }

  return (
    <Cascader
      value={innerValue}
      options={options}
      {...cascaderProps}
      disabled={disabled}
      displayRender={(labels) => labels[labels.length - 1]}
      size={size}
      style={{ width: '100%' }}
      onChange={handleChange}
    />
  );
};

export default DataTypeSelect; 